package com.ericom.webapp.action;

import java.util.List;

import com.ericom.model.Product;
import com.ericom.service.GenericManager;

public class ProductAction extends BaseAction {
	private GenericManager<Product, Long> productManager;
	private List products;
	private Product product;
	private Long id;

	public Product getProduct() {
		return product;
	}

	public void setProduct(Product product) {
		this.product = product;
	}

	public void setId(Long id) {
		this.id = id;
	}

	public void setProductManager(GenericManager<Product, Long> productManager) {
		this.productManager = productManager;
	}

	public String list() {
		products = productManager.getAll();
		return SUCCESS;
	}

	public List getProducts() {
		return products;
	}

	public String delete() {
		productManager.remove(product.getId());
		this.saveMessage(getText("product.deleted"));
		return this.SUCCESS;
	}

	public String edit() {
		if (id != null) {
			product = productManager.get(id);
		} else {
			product = new Product();
		}
		return this.SUCCESS;
	}

	public String save() throws Exception {
		if (this.cancel != null) {
			return this.CANCEL;
		}
		if (this.delete != null) {
			return this.delete();
		}

		boolean isNew = (product.getId() == null);
		product = productManager.save(product);

		String key = (isNew) ? "product.added" : "product.updated";
		this.saveMessage(getText(key));

		if (!isNew) {
			return this.INPUT;
		} else {
			return this.SUCCESS;
		}
	}
}
